var main = angular.module('main');

main.controller('apisCtrl', ['$scope', 'http', '$stateParams', function($scope, http, $stateParams) {
    $scope.newGroup = "";
    $scope.groups = [{ id: -1, name: '所有分组' }];
    $scope.groupSelected = $scope.groups[0].id;
    $scope.sortBy = "time";
    $scope.finish = "all";
    $scope.api2delete = null;

    $scope.project_id = $stateParams.project_id;
    http.post('/api/group/list', { project_id: $scope.project_id }).then(function(data) {
        $scope.groups = $scope.groups.concat(data.data);
    });
    $scope.addGroup = function() {
        if ($scope.newGroup) {
            http.post('/api/group/add', { project_id: $scope.project_id, name: $scope.newGroup }).then(function(data) {

                http.post('/api/group/list', { project_id: $scope.project_id }).then(function(data) {
                    $scope.groups = $scope.groups.concat(data.data);
                });
                $scope.newGroup = "";
            });
        } else
            alert("分组名不能为空");
    };

    http.post('/api/list', { project_id: $scope.project_id, sort: 'time', offset: 0, count: 20 }).then(function(data) {
        $scope.apiList = data.data.api_list;
    });

    $scope.query = function() {
        var d = { project_id: $scope.project_id, sort: $scope.sortBy, offset: 0, count: 20 };
        if ($scope.group_id != -1) {
            d.group_id = $scope.groupSelected;
        }
        if ($scope.finish != 'all') {
            d.finished = ($scope.finish === 'finished' ? true : false);
        }

        http.post('/api/list', d).then(function(data) {
            $scope.apiList = data.data.api_list;
        });
    };

    $scope.deleteApiHelp = function(api) {
        $scope.api2delete = api;
    };

    $scope.deleteApi = function(api) {
        var modal=UIkit.modal('#deleteDialog');
        modal.hide();
        http.post('/api/delete', { api_id: api.id }).then(function(data) {
            var index = $scope.apiList.indexOf(api);
            $scope.apiList.splice(index, 1);
        });
    };
}]);
